package com.iwaster.dao.impl;

import com.iwaster.dao.StudentDao;
import com.iwaster.domain.Student;
import com.iwaster.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * wgy 2019/4/23 14:14
 */
public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> findByPage(int pageIndex, int pageSize) {  //1  20   2  20
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return qr.query("select * from student order by studentNo limit ?,?", new BeanListHandler<>(Student.class),(pageIndex-1)*pageSize,pageSize);
        } catch (Exception e) {
            throw  new RuntimeException("分页查询失败",e);
        }
    }

    @Override
    /*
     */
    public void add(Student stu) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        try {
            qr.update("insert into student(studentNo,loginPwd,studentName,sex,bornDate) values(?,?,?,?,?);", stu.getStudentNo(), stu.getLoginPwd(), stu.getStudentName(), stu.getSex(), stu.getBornDate());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("添加失败", e);
        }
    }

    @Override
    public long getCount() {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return qr.query("select count(*) from student", new ScalarHandler<>());
        } catch (Exception e) {
            throw  new RuntimeException("获取数据个数失败",e);
        }
    }
}
